import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:permission_handler/permission_handler.dart';

import 'index.dart';
import '../../../common/utils/index.dart';

class TestPermissionPage extends GetView<TestPermissionController> {
  const TestPermissionPage({super.key});

  // 主视图
  Widget _buildView() {
    return SingleChildScrollView(
      padding: const EdgeInsets.all(20.0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          const SizedBox(height: 20),
          
          // 页面图标和标题
          _buildHeader(),
          
          const SizedBox(height: 40),
          
          // 权限项目列表
          _buildPermissionList(),
          
          const SizedBox(height: 40),
          
          // 底部提示
          HintTipWidget.success(
            text: '权限测试页面加载成功！',
          ),
          
          const SizedBox(height: 16),
          
          // 设置说明提示
          Container(
            padding: const EdgeInsets.all(16),
            decoration: BoxDecoration(
              color: Colors.amber.shade50,
              borderRadius: BorderRadius.circular(12),
              border: Border.all(
                color: Colors.amber.shade200,
                width: 1,
              ),
            ),
            child: Row(
              children: [
                Icon(
                  Icons.lightbulb_outline,
                  color: Colors.amber.shade600,
                  size: 20,
                ),
                const SizedBox(width: 12),
                Expanded(
                  child: Text(
                    '如果权限被永久拒绝，请使用"打开应用设置"按钮手动开启权限',
                    style: TextStyle(
                      fontSize: 12,
                      color: Colors.amber.shade800,
                      height: 1.3,
                    ),
                  ),
                ),
              ],
            ),
          ),
          
          const SizedBox(height: 20),
        ],
      ),
    );
  }

  // 构建页面头部
  Widget _buildHeader() {
    return Column(
      children: [
        Container(
          width: 80,
          height: 80,
          decoration: BoxDecoration(
            gradient: LinearGradient(
              colors: [Colors.orange.shade400, Colors.orange.shade600],
              begin: Alignment.topLeft,
              end: Alignment.bottomRight,
            ),
            shape: BoxShape.circle,
            boxShadow: [
              BoxShadow(
                color: Colors.orange.withOpacity(0.3),
                blurRadius: 15,
                offset: const Offset(0, 5),
              ),
            ],
          ),
          child: const Icon(
            Icons.security,
            color: Colors.white,
            size: 40,
          ),
        ),
        const SizedBox(height: 20),
        const Text(
          '权限测试',
          style: TextStyle(
            fontSize: 28,
            fontWeight: FontWeight.bold,
            color: Colors.black87,
          ),
        ),
        const SizedBox(height: 8),
        Text(
          '测试应用权限请求和管理',
          style: TextStyle(
            fontSize: 16,
            color: Colors.grey.shade600,
          ),
        ),
      ],
    );
  }

  // 构建权限列表
  Widget _buildPermissionList() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        // 权限统计信息
        _buildPermissionStats(),
        
        const SizedBox(height: 20),
        
        const Text(
          '权限项目',
          style: TextStyle(
            fontSize: 20,
            fontWeight: FontWeight.w600,
            color: Colors.black87,
          ),
        ),
        
        const SizedBox(height: 16),
        
        // 权限项目列表
        ...controller.permissionList.asMap().entries.map((entry) {
          final index = entry.key;
          final permission = entry.value;
          return _buildPermissionItem(permission, index);
        }).toList(),
        
        const SizedBox(height: 20),
        
        // 重置按钮
        _buildResetButton(),
        
        const SizedBox(height: 12),
        
        // 应用设置按钮
        _buildAppSettingsButton(),
      ],
    );
  }

  // 构建权限统计信息
  Widget _buildPermissionStats() {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        gradient: LinearGradient(
          colors: [Colors.blue.shade50, Colors.blue.shade100],
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
        ),
        borderRadius: BorderRadius.circular(12),
        border: Border.all(
          color: Colors.blue.withOpacity(0.2),
          width: 1,
        ),
      ),
      child: Row(
        children: [
          Icon(
            Icons.analytics_outlined,
            color: Colors.blue.shade600,
            size: 24,
          ),
          const SizedBox(width: 12),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                const Text(
                  '权限统计',
                  style: TextStyle(
                    fontSize: 14,
                    fontWeight: FontWeight.w600,
                    color: Colors.black87,
                  ),
                ),
                const SizedBox(height: 4),
                Text(
                  '已测试: ${controller.testedPermissionsCount.value} / ${controller.permissionList.length}',
                  style: TextStyle(
                    fontSize: 12,
                    color: Colors.grey.shade600,
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  // 构建单个权限项目
  Widget _buildPermissionItem(Permission permission, int index) {
    final isSelected = controller.selectedPermissionIndex.value == index;
    final status = controller.permissionStatus[permission] ?? PermissionStatus.denied;
    final statusColor = _getPermissionStatusColor(status);
    final statusText = _getPermissionStatusText(status);
    
    return Container(
      margin: const EdgeInsets.only(bottom: 12),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12),
        boxShadow: [
          BoxShadow(
            color: isSelected 
                ? Colors.orange.withOpacity(0.2) 
                : Colors.grey.withOpacity(0.1),
            blurRadius: isSelected ? 12 : 8,
            offset: const Offset(0, 2),
          ),
        ],
        border: Border.all(
          color: isSelected 
              ? Colors.orange.withOpacity(0.4) 
              : Colors.grey.withOpacity(0.2),
          width: isSelected ? 2 : 1,
        ),
      ),
      child: Material(
        color: Colors.transparent,
        child: InkWell(
          onTap: () => controller.testPermission(index),
          borderRadius: BorderRadius.circular(12),
          child: Padding(
            padding: const EdgeInsets.all(16),
            child: Row(
              children: [
                // 权限图标
                Container(
                  width: 40,
                  height: 40,
                  decoration: BoxDecoration(
                    color: statusColor.withOpacity(0.1),
                    borderRadius: BorderRadius.circular(8),
                  ),
                  child: Icon(
                    _getIconFromString(controller.getPermissionIconName(permission)),
                    color: statusColor,
                    size: 20,
                  ),
                ),
                
                const SizedBox(width: 16),
                
                // 权限信息
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        controller.getPermissionName(permission),
                        style: const TextStyle(
                          fontSize: 16,
                          fontWeight: FontWeight.w500,
                          color: Colors.black87,
                        ),
                      ),
                      const SizedBox(height: 4),
                      Text(
                        controller.getPermissionDescription(permission),
                        style: TextStyle(
                          fontSize: 12,
                          color: Colors.grey.shade600,
                        ),
                      ),
                    ],
                  ),
                ),
                
                // 状态指示器
                _buildStatusIndicator(status, statusText, permission),
              ],
            ),
          ),
        ),
      ),
    );
  }

  // 构建状态指示器
  Widget _buildStatusIndicator(PermissionStatus status, String statusText, [Permission? permission]) {
    switch (status) {
      case PermissionStatus.provisional:
        return Container(
          width: 20,
          height: 20,
          child: CircularProgressIndicator(
            strokeWidth: 2,
            valueColor: AlwaysStoppedAnimation<Color>(Colors.orange.shade600),
          ),
        );
      
      case PermissionStatus.limited:
        // limited状态的权限显示为可点击的状态指示器
        return GestureDetector(
          onTap: permission != null ? () => controller.showPermissionDetails(permission) : null,
          child: Container(
            padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
            decoration: BoxDecoration(
              color: _getPermissionStatusColor(status).withOpacity(0.1),
              borderRadius: BorderRadius.circular(6),
              border: Border.all(
                color: _getPermissionStatusColor(status).withOpacity(0.3),
                width: 1,
              ),
            ),
            child: Row(
              mainAxisSize: MainAxisSize.min,
              children: [
                Text(
                  statusText,
                  style: TextStyle(
                    fontSize: 12,
                    color: _getPermissionStatusColor(status),
                    fontWeight: FontWeight.w500,
                  ),
                ),
                const SizedBox(width: 4),
                Icon(
                  Icons.info_outline,
                  size: 14,
                  color: _getPermissionStatusColor(status),
                ),
              ],
            ),
          ),
        );
      
      default:
        return Container(
          padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
          decoration: BoxDecoration(
            color: _getPermissionStatusColor(status).withOpacity(0.1),
            borderRadius: BorderRadius.circular(6),
          ),
          child: Text(
            statusText,
            style: TextStyle(
              fontSize: 12,
              color: _getPermissionStatusColor(status),
              fontWeight: FontWeight.w500,
            ),
          ),
        );
    }
  }

  // 构建重置按钮
  Widget _buildResetButton() {
    return SizedBox(
      width: double.infinity,
      height: 48,
      child: ElevatedButton.icon(
        onPressed: controller.testedPermissionsCount.value > 0 
            ? controller.resetAllPermissions 
            : null,
        icon: const Icon(Icons.refresh, size: 20),
        label: const Text(
          '重置所有权限',
          style: TextStyle(fontSize: 16, fontWeight: FontWeight.w500),
        ),
        style: ElevatedButton.styleFrom(
          backgroundColor: Colors.grey.shade100,
          foregroundColor: Colors.grey.shade700,
          elevation: 0,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(12),
          ),
        ),
      ),
    );
  }

  // 构建应用设置按钮
  Widget _buildAppSettingsButton() {
    return SizedBox(
      width: double.infinity,
      height: 48,
      child: ElevatedButton.icon(
        onPressed: controller.openAppSettings,
        icon: Icon(
          Icons.settings,
          size: 20,
          color: Colors.blue.shade600,
        ),
        label: Text(
          '打开应用设置',
          style: TextStyle(
            fontSize: 16,
            fontWeight: FontWeight.w500,
            color: Colors.blue.shade700,
          ),
        ),
        style: ElevatedButton.styleFrom(
          backgroundColor: Colors.blue.shade50,
          foregroundColor: Colors.blue.shade700,
          elevation: 0,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(12),
            side: BorderSide(
              color: Colors.blue.shade200,
              width: 1,
            ),
          ),
        ),
      ),
    );
  }

  // 辅助方法：根据字符串获取图标
  IconData _getIconFromString(String iconName) {
    switch (iconName) {
      case 'camera_alt':
        return Icons.camera_alt;
      case 'photo_library':
        return Icons.photo_library;
      case 'location_on':
        return Icons.location_on;
      case 'mic':
        return Icons.mic;
      case 'notifications':
        return Icons.notifications;
      default:
        return Icons.security;
    }
  }

  // 辅助方法：获取权限状态颜色
  Color _getPermissionStatusColor(PermissionStatus status) {
    switch (status) {
      case PermissionStatus.granted:
        return Colors.green.shade600;
      case PermissionStatus.denied:
        return Colors.red.shade600;
      case PermissionStatus.provisional:
        return Colors.orange.shade600;
      case PermissionStatus.permanentlyDenied:
        return Colors.red.shade800;
      case PermissionStatus.restricted:
        return Colors.purple.shade600;
      case PermissionStatus.limited:
        return Colors.lightGreen.shade600; // 改为浅绿色，表示可用状态
    }
  }

  // 辅助方法：获取权限状态文本
  String _getPermissionStatusText(PermissionStatus status) {
    switch (status) {
      case PermissionStatus.granted:
        return '已授权';
      case PermissionStatus.denied:
        return '未测试';
      case PermissionStatus.provisional:
        return '测试中';
      case PermissionStatus.permanentlyDenied:
        return '永久拒绝';
      case PermissionStatus.restricted:
        return '受限制';
      case PermissionStatus.limited:
        return '部分授权'; // iOS相册"选择照片"模式，仍可正常使用
    }
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder<TestPermissionController>(
      id: "test_permission",
      builder: (_) {
        // 加载状态显示
        if (!controller.isInitialized.value) {
          return Scaffold(
            appBar: AppBar(
              leading: IconButton(
                icon: Icon(Icons.arrow_back_ios, color: Colors.black87, size: 20),
                onPressed: () => Get.back(),
              ),
              title: Text(controller.pageTitle),
              backgroundColor: Colors.transparent,
              elevation: 0,
            ),
            body: const Center(
              child: CircularProgressIndicator(),
            ),
          );
        }

        return Scaffold(
          appBar: AppBar(
            leading: IconButton(
                icon: Icon(Icons.arrow_back_ios, color: Colors.black87, size: 20),
                onPressed: () => Get.back(),
              ),
            title: Text(
              controller.pageTitle,
              style: const TextStyle(
                fontSize: 18,
                fontWeight: FontWeight.w600,
              ),
            ),
            backgroundColor: Colors.white,
            elevation: 0,
            scrolledUnderElevation: 0,
            surfaceTintColor: Colors.transparent,
            foregroundColor: Colors.black87,
            systemOverlayStyle: const SystemUiOverlayStyle(
              statusBarColor: Colors.transparent,
              statusBarIconBrightness: Brightness.dark,
            ),
            actions: [
              // 权限统计图标
              IconButton(
                onPressed: () {
                  final stats = controller.getPermissionStats();
                  // Get.snackbar(
                  //   '权限统计',
                  //   '已授权: ${stats[PermissionStatus.granted] ?? 0}\n'
                  //   '部分授权: ${stats[PermissionStatus.limited] ?? 0}\n'
                  //   '被拒绝: ${stats[PermissionStatus.denied] ?? 0}\n'
                  //   '永久拒绝: ${stats[PermissionStatus.permanentlyDenied] ?? 0}',
                  //   duration: const Duration(seconds: 3),
                  //   backgroundColor: Colors.blue.shade50,
                  //   colorText: Colors.black87,
                  // );
                },
                icon: const Icon(Icons.info_outline),
                tooltip: '查看权限统计',
              ),
              
              // 应用设置图标
              Padding(
                padding: const EdgeInsets.only(right: 8.0),
                child: IconButton(
                  onPressed: controller.openAppSettings,
                  icon: const Icon(Icons.settings),
                  tooltip: '打开应用设置',
                ),
              ),
            ],
          ),
          body: SafeArea(
            child: _buildView(),
          ),
        );
      },
    );
  }
}
